package org.tgcloud.group.core.fileUtils.waterMarkFileUtils;

import java.awt.image.BufferedImage;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;
/**
 * 图片压缩
 * @author 86183
 *
 */
@SuppressWarnings("restriction")
public class ImgCompress {
    static BufferedImage img = null;

    public static void main(String[] args) throws IOException {

        String fromPic = "D:\\图片壁纸\\图片\\pic_big.png";
        String toPic = "D:\\图片壁纸\\图片\\pic_big.png";
        File imageFile = new File(fromPic);
        int width = 400;
        int height = 400;
        try {
            BufferedImage image = ImageIO.read(imageFile);
            width = image.getWidth();
            height = image.getHeight();
            System.out.println("图片的宽度：" + width);
            System.out.println("图片的高度：" + height);
        } catch (IOException e) {
            e.printStackTrace();
        }
        ImgCompress imgCom = new ImgCompress(fromPic);
        imgCom.resize(width, height, toPic);
    }
    /**
     * 构造函数
     */
    public ImgCompress(String fileName) throws IOException {

        File file = new File(fileName);// 读入文件
        img = ImageIO.read(file);      // 构造Image对象
    }

    /**
     * 强制压缩/放大图片到固定的大小
     *
     * @param w int 新宽度
     * @param h int 新高度
     */
    public void resize(int w, int h, String toPic) throws IOException {
        // SCALE_SMOOTH 的缩略算法 生成缩略图片的平滑度的 优先级比速度高 生成的图片质量比较好 但速度慢
        BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        image.getGraphics().drawImage(img, 0, 0, w, h, null); // 绘制缩小后的图
        File destFile = new File(toPic);

        FileOutputStream out = new FileOutputStream(destFile); // 输出到文件流
        // 可以正常实现bmp、png、gif转jpg
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
        encoder.encode(image); // JPEG编码
        out.close();
    }
}